const remoteVideo = document.getElementById('remoteVideo');
const startButton = document.getElementById('start');

let peerConnection;
let socket;

const servers = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' }
    ]
};

function start() {
    createPeerConnection();
}

function createPeerConnection() {
    peerConnection = new RTCPeerConnection(servers);

    peerConnection.ontrack = handleRemoteTrack;
    peerConnection.onicecandidate = handleIceCandidate;

    // 创建WebSocket连接
    socket = new WebSocket('wss://192.168.2.46:8080/websocket');

    socket.onopen = () => {
        console.log('WebSocket connection established');
    };

    socket.onmessage = event => {
        const data = JSON.parse(event.data);
        console.log('Received message:', data);
        if (data.type === 'offer') {
            peerConnection.setRemoteDescription(new RTCSessionDescription(data))
                .then(() => createAnswer())
                .catch(error => console.error('Error setting remote description:', error));
        } else if (data.type === 'candidate') {
            peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                .catch(error => console.error('Error adding ICE candidate:', error));
        }
    };

    socket.onerror = error => {
        console.error('WebSocket error:', error);
    };

    socket.onclose = () => {
        console.log('WebSocket connection closed');
        socket = null;
    };
}

function handleRemoteTrack(event) {
    console.log('Remote track received:', event.streams[0]);
    remoteVideo.srcObject = event.streams[0];
    console.log('Remote video srcObject set:', remoteVideo.srcObject);
}

function handleIceCandidate(event) {
    if (event.candidate) {
        sendSignalingMessage({ type: 'candidate', candidate: event.candidate });
    }
}

function sendSignalingMessage(message) {
    console.log("Sending signaling message:", message);
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify(message));
    } else {
        console.warn('WebSocket is not open. Ready state:', socket ? socket.readyState : 'null');
    }
}

function createAnswer() {
    peerConnection.createAnswer()
        .then(answer => peerConnection.setLocalDescription(answer))
        .then(() => sendSignalingMessage(peerConnection.localDescription))
        .catch(error => console.error('Error creating answer:', error));
}

startButton.addEventListener('click', start);
